<?php
class OrderModel extends Model
{
    public $errorinfo = '';
    public function _list($map, $sort = 'sort', $pagesize = 20)
    {
        //计算总页数
        $count = $this->where($map)->count();
        //实例化分页类
        import('ORG.Util.Page');
        $p = new Page($count, $pagesize);
        $list = $this->where($map)->order($sort)->limit($p->firstRow . ',
' . $p->listRows)->select();
        //$goods = $this->where('')
        $pages = $p->show();
        $data['list'] = $list;
        $data['pages'] = $pages;
        return $data;
    }
    //处理订单支付状态
    public function upstate($ordernumber)
    {
        $order = M('order');
        $memberDB = M('member');
        $saleDB = M("Sale");
        $restult = $order->where(array('ordernumber' => $ordernumber, 'site_id' => __SITEID__))->find();
        if ($restult['status'] == 1) {
            $saleDB->data(array('pay_status' => 1))->where(array('order_id' => $restult['id']))->save();
            $mes = $order->where(array('ordernumber' => $ordernumber))->save(array('status' => 2));
            $res = D('Order_supplier')->where(array('ordernumber' => $ordernumber))->save(array('status' => 2));
            if ($mes) {
				//写入消费金额
				$memberDB -> where(array('id' => $restult['member_id'])) -> setInc('salesum', $restult['total']);
                //修改推荐人与订单对应关系的订单状态
                M('Membermembersale')->where(array('order_id' => $restult['id']))->data(array('pay_status' => 1))->save();
                //自动开通后台用户和站点
                if ($restult['siteid'] > 0 && $restult['is_renew'] == 0) {
                    @curlRequest(U('Home/Ajax/createSite', array('order_id' => $restult['id']), true, false, true, __SITEID__));
                }
				//站点续费
				if ($restult['is_renew'] > 0) {
                    @curlRequest(U('Home/Ajax/renewSite', array('order_id' => $restult['id']), true, false, true, __SITEID__));
                }
                //分成写入
				//用户充值处理
                if ($restult['savemoney'] > 0) {
                    D('Member')->savemoney($restult['id']);
                }
                $afflist = $payment = M('Affiliatesetting')->where(array('site_id' => $restult['relate_id'], 'status' => 1))->select();
                foreach ($afflist as $v) {
                    import("@.ORG.Affiliate." . $v['classname']);
                    $class = $v['classname'];
                    $Threelevel = new $class($restult['id'], $restult['relate_id']);
                    $Threelevel->insertlog();
                }
                //商家分成
                $bns = M('business_site')->where(array('site_id' => $restult['site_id']))->count();
                //F('data',$bns);
                if ($bns > 0) {
                    import("@.ORG.Business.Business");
                    $Business = new Business($restult['id']);
                    $Business->setbusiness();
                }
                //处理拼团
                $Grouppurchase = D('Grouppurchase');
                $saleList = $saleDB->alias('s')->join("left join __PRODUCT__ AS p on p.id = s.product_id")->where(array('order_id' => $restult['id']))->Field("s.*,p.coupon_id,p.servicecard_id, p.autoconfirm, p.socre, p.status as pstatus")->select();
                import("@.ORG.Coupon.Coupon");
                import("@.ORG.Cashback.Cashback");
                //赠送积分
                $socre = 0;
                foreach ($saleList as $v) {
					if($v['pstatus'] == -1){
						$orderDB=D('order');
                        $end=$orderDB->confirm($restult['id'],$restult['site_id']);
					}
                    $socre += $v['socre'];
                    $Cashback_config = M('Cashback_config')->where(array('status' => 1, 'product_id' => $v['product_id']))->find();
                    if ($Cashback_config) {
                        $Cashback = new Cashback($v);
                        if ($Cashback->canCashback()) {
                            // 增加返现总额、余额操作
                            $Cashback->addMoney();
                        }
                    }
                    //自动确认
                    if ($v['autoconfirm'] == 1) {
                        $saleDB->where(array('id' => $v['id']))->data(array('status' => 1, 'confirm' => 1))->save();
                        //订单中只有一个商品的情况下，订单必须全部确认，否则部分确认
                        if (count($saleList) > 1) {
                          //  M('Order')->where(array('id' => $restult['id']))->data(array('shipping_status' => 1))->save();
							$this->confirm($restult['id'],$v['id']);
                        } else {
						//$this->confirm($restult['id'],$v['id']);
                           // M('Order')->where(array('id' => $restult['id']))->data(array('shipping_status' => 4, 'confirm' => 1))->save();
                        }
                    }
                    if ($v['coupon_id'] > 0) {
                        $Coupon = new Coupon($v['coupon_id'], "0");
                        if ($Coupon->canTake($v['member_id'])) {
                            $Coupon->getCoupon($v['member_id']);
                        }
                    }
                    //送服务卡
                    if ($v['servicecard_id'] > 0) {
                        D('Servicecard')->sendCard($v['servicecard_id'], $v['member_id'], $v['id'], $v['order_id']);
                    }
                    $Grouppurchase->insertOrder($v['id']);
                }
                //返回赠送积分
                import("@.ORG.Integrals.Integral");
                $Integral = new Integral($restult['member_id']);
                $Integral->giveIntegral($socre);
                //支付成功提示
                $sale = $saleDB->where(array('order_id' => $restult['id']))->select();
                $content = array();
                $domain = M('Site')->where(array('id' => __SITEID__))->getField('domain');
                if ($domain == '') {
                    $siteid = __SITEID__;
                } else {
                    $siteid = 0;
                }
                $content[0] = array("title" => "支付通知",
                    "description" => "您得订单:" . $restult['ordernumber'] . "成功支付\n"
                        . "总额:" . $restult['total'] . "元",
                    "picurl" => "http://" . $_SERVER['HTTP_HOST'] . "/Public" . $sale[0]['img_url'],
                    "url" => U('Member/Order/read', array('id' => $restult['id']), true, false, true, $siteid),
                );
                $member = $memberDB->where(array('id' => $restult['member_id']))->find();
$send=array();
                sendWXNews($member['openid'], $content);
				$sale = $saleDB->where(array('order_id' => $restult['id']))->select();
				foreach($sale as $sk => $sv){
				$product=M('Product')->where(' id = '.$sv['product_id'])->getField('supplier_id');	
				$mid=M('Supplier')->where(' id = '.$product)->getField('member_id');
				$member=M('Member')->where('id = '.$mid)->find();
				$content[0]['description']='订单:' . $restult['ordernumber'] . "成功支付\n"."总额:" . $restult['total'] . "元";
				if($send!=NULL){
					foreach($send as  $ssk => $ssv){
						if($ssv==$member['openid']){
							$a=1;	
						}
					}
					if($a!=1){
					$send[]=$member['openid'];	
					}
				}else{
					$send[]=$member['openid'];	
				}
				}
				foreach($send as $k => $v){
				 sendWXNews($v, $content);
				}
                return true;
            } else {
                return false;
            }
        }
    }
    //更新库存
    public function updateStock($order_id)
    {
        $db = M('Sale');
        $order = $this->where(array('id' => $order_id))->find();
        $productList = $db->alias('s')->where(array('s.order_id' => $order_id))->join("left join __PRODUCT__ as p on p.id=s.product_id")->Field("s.num,s.price,p.*,s.attr")->select();
        $num = 0;
        $stockdb = M('Product_stock');
        $productDB = M('Product');
        //客户已经下单
        if ($order['status'] == 1) {
            foreach ($productList as $k => $v) {
                //更新总库存
                $num += $v['num'];
                if ($v['attr'] != '') {
                    $map['attrList'] = array('in', parseAttrId(explode(';', $v['attr'])));
                    $stockdb->where($map)->setDec('stock', $v['num']);
                }
                $map1['id'] = $v['id'];
                $productDB->where($map1)->setDec('stocks', $v['num']);
                //if(__SITEID__ == 13){F('stocks', $productDB->getLastSql());}
                $productDB->where($map1)->setInc('salecount', $v['num']);
            }
        }
        //取消订单
        if ($order['status'] == 0) {
            foreach ($productList as $k => $v) {
                //更新总库存
                $num += $v['num'];
                if ($v['attr'] != '') {
                    $map['attrList'] = array('in', parseAttrId(explode(';', $v['attr'])));
                    $stockdb->where($map)->setInc('stock', $v['num']);
                }
                $map1['id'] = $v['id'];
                $productDB->where($map1)->setInc('stocks', $v['num']);
            }
        }
    }
//获取所有订单商品
    public function getAllProduct($oid,$supplier_id='')
    {
        if($supplier_id!=''){
            $where=array('s.order_id' => $oid,'s.supplier_id'=>$supplier_id);
        }else{
            $where=array('s.order_id' => $oid);
        }
        $db = M('Sale');
        $list = $db->alias('s')->where($where)->join("left join __PRODUCT__ as p on p.id=s.product_id")->Field("s.id as sale_id,s.product_id as product_id,s.supplier_id as supplierid,s.num,s.attr,s.total,s.price,s.pay_status as pay_status,s.status as shippingstatus,p.*")->select();
        //获取商品属性
        $attrvalDB = M('attr_val');
        foreach ($list as $k => $v) {
            $attrval = explode(';', $v['attr']);
            $list[$k]['attrmes'] = array();
            $list[$k]['RebateModel']=D('Product')->where('id = '.$v['product_id'])->getfield('RebateModel');
            foreach ($attrval as $v) {
                $mes = $attrvalDB->where(array('id' => $v))->find();
                array_push($list[$k]['attrmes'], $mes['val']);
            }
        }
        return $list;
    }
    //更新订单发货状态
    public function updateshipping($order_id, $site_id = 0)
    {
        $saledb = M('Sale');
        if ($saledb->where(array('order_id' => $order_id, 'status' => 1, 'site_id' => $site_id))->getField('count(*) as tp') == 0) {
            return;
        }
        $ret = $saledb->where(array('order_id' => $order_id, 'site_id' => $site_id))->group('status')->Field('count(status)')->select();
        $status = 1;
        if (count($ret) == 1) {
            $status = 2;
        }
        $this->where(array('id' => $order_id, 'site_id' => $site_id))->data(array('shipping_status' => $status))->save();
        if ($saledb->where(array('order_id' => $order_id, 'confirm' => 1, 'status' => 1, 'site_id' => $site_id))->getField('count(*) as tp') == 0) {
            return;
        }
        $ret = $saledb->where(array('order_id' => $order_id, 'site_id' => $site_id))->group('confirm')->Field('count(confirm)')->select();
        $status = 3;
        if (count($ret) == 1) {
            $status = 4;
        }
        $this->where(array('id' => $order_id, 'site_id' => $site_id))->data(array('shipping_status' => $status))->save();
    }
    //发货操作
    public function delivery($order_id, $site_id = 0, $supplier)
    {
    }
    //更新订单为收货状态
    public function confirm($order_id, $site_id = 0)
    {
		
		$order=M('Order')->where(' id = '.$order_id)->find();
		if($order['confirm']==1){
		$this->error('请不要重复确认订单！');
		exit();	
		}
        if (intval($order_id) == 0) {
            return false;
        }
        $saleDB = M('Sale');
        $sale = $saleDB->where(array(
            'order_id' => $order_id,
            'site_id' => $site_id
        ))->select();
        foreach ($sale as $k => $v) {
            if ($v['thstatus'] == 1 || $v['thstatus'] == 2 || $v['thstatus'] == 3 || $v['thstatus'] == 5) {
                $this->errorinfo = '订单正在售后，不能完成订单';
                return false;
            }
 
        }
		//exit(dump(1));		
        $ret = $this->where(array('id' => $order_id, 'site_id' => $site_id))->data(array('confirm' => 1))->save();
		
 $afflist = $payment = M('Affiliatesetting')->where(array('site_id' => __SITEID__, 'status' => 1))->select();
                foreach ($afflist as $v) {
				
                    import("@.ORG.Affiliate." . $v['classname']);
                    $class = $v['classname']; 
				
                    $Threelevel = new $class($order_id, __SITEID__,$order['member_id']);
					$affsettingarr=unserialize($afflist[0]['value']);
					
					foreach($sale as $sk => $sv){
					foreach($affsettingarr['levelbuy'] as $fk => $fv){
					
					if($sv['product_id']==$fv){
					 $Threelevel->insertlog();
					}
					}
					}
                }
			
        if ($ret !== false) {/*
            //先找member_account_log中是否有此订单的分成记录，有就直接用此表按供销商分货款
            $check = D('member_account_log')->where(array('order_id'=>$order_id,'site_id'=>$site_id,'product_id' => array('GT','0')))->select();
            if($check){//有分成
                $show = D('member_account_log')->where(array('order_id'=>$order_id,'site_id'=>$site_id))->group('product_id')->Field("*,sum('affmoney')")->select();
                foreach ($show as $key => $value) {
                    $data['changenum']=$value['goodsMoney']-$val['sum'];
                    $data['product_id']=$value['product_id'];
                    $num=$v['num'];
                    $pro_name=D('product')->where('id = '.$data['product_id'])->getField('title');
                    $data['order_id']=$value['order_id'];
                    $data['deteline']= time();
                    $data['site_id']=$site_id;
                    $ordernum=D('order')->where(array('order_id'=>$order_id,'site_id'=>$site_id))->getField('ordernumber');
                    $name    =D('order')->where(array('order_id'=>$order_id,'site_id'=>$site_id))->getField('nickname');
                    $data['remark']='用户：'.$name.'，商品：'.$pro_name.','.$num.'件，订单:'.$ordernum.'完成';
                    if($value['product_id']>0)
                    {
                        $data['supplier_id']=D('product')->where("id = ".$value['product_id'])->getField('supplier_id');
                    }else{
                        $data['supplier_id']='0';
                    }
                    $add=D('supplier_account_log')->add($data);
                    if($add){
                        //判断supplier_id是否有对应的member_id，如果有，往供货商账户member_account_log，写入金额，备注'供货商结算'
                        $sup=D('member_supplier')->where(array('supplier_id'=>$data['supplier_id'],'site_id'=>$site_id))->find();
                        if($sup){
                            $member['site_id']      =$site_id;//网点
                            $member['member_id']    = $sup['member_id'];//会员号
                            $member['datetime']     =time();//时间
                            $member['remark']       ='供货商结算';//备注
                            $member['changenum']    =$data['changenum'];//金额
                            $memberAdd=D('member_account_log')->add($member);
                            if($memberAdd){//往member表写入数据！！！
                                $oldmoney=D('member')->where(array('id'=>$member['member_id']))->getField('money');
                                $default['money']=$member['changenum']+$oldmoney;
                                $count=D('member')->where(array('id'=>$member['member_id']))->save($default);
                                if($count){
                                    return true;
                                }else{
                                    return false;
                                }
                            }else{
                                return false;
                            }
                        }
                        return true;
                    }else{
                        return false;
                    }
                }
            }else{//无分成
                //如果没有分成记录，就到sale表中查此订单的商品记录,按照不同product_id区分不同的supplier_id，
                //进而找到total字段统计各个不同供销商的金额
                $sale=D('sale')->where(array('order_id'=>$order_id,'site_id'=>$site_id))->select();//在sale表查找当前订单
                foreach ($sale as $k => $v) {//每一个order_id
                    $data['order_id']=$v['order_id'];
                    $data['supplier_id']=$v['supplier_id'];
                    $data['product_id']=$v['product_id'];
                    $num=$v['num'];
                    $pro_name=D('product')->where('id = '.$data['product_id'])->getField('title');
                    $data['changenum']=$v['total'];
                    $data['dateline']=time();
                    $data['site_id']=$site_id;
                    $ordernum   =D('order')->where(array('id'=>$order_id,'site_id'=>$site_id))->getField('ordernumber');
                    $name       =D('order')->where(array('id'=>$order_id,'site_id'=>$site_id))->getField('nickname');
                    $data['remark']='用户：'.$name.'，商品：'.$pro_name.','.$num.'件，订单:'.$ordernum.'完成';
                    $add=D('supplier_account_log')->add($data);
                    if($add){
                        //判断supplier_id是否有对应的member_id，如果有，往供货商账户member_account_log，写入金额，备注'供货商结算'
                        $sup=D('member_supplier')->where(array('supplier_id'=>$data['supplier_id'],'site_id'=>$site_id))->find();
                        if($sup){
                            $member['site_id']      =$site_id;//网点
                            $member['member_id']    = $sup['member_id'];//会员号
                            $member['datetime']     =time();//时间
                            $member['remark']       ='供货商结算';//备注
                            $member['changenum']    =$data['changenum'];//金额
                            $memberAdd=D('member_account_log')->add($member);
                            if($memberAdd){//往member表写入数据！！！
                                $oldmoney=D('member')->where(array('id'=>$member['member_id']))->getField('money');
                                $default['money']=$member['changenum']+$oldmoney;
                                $count=D('member')->where(array('id'=>$member['member_id']))->save($default);
                                if($count){
                                    return true;
                                }else{
                                    return false;
                                }
                            }else{
                                return false;
                            }
                        }
                        return true;
                    }else{
                        return false;
                    }
                }
            }
        */
            //先找member_account_log中是否有此订单的分成记录，有就直接用此表按供销商分货款
            //查找销售记录
            $salelist = D('Sale')->where(array('order_id' => $order_id))->select();
            foreach ($salelist as $key => $value) {
				
				$affmoneytotal = (float)M('Member_account_log') -> where(array('sale_id' => $value['id'], 'pdstate' => 3)) -> sum('changenum');
                $data['changenum'] = $value['total'] - $affmoneytotal;
                $data['product_id'] = $value['product_id'];
                $num = $v['num'];
                $pro_name = D('Product')->where('id = ' . $data['product_id'])->getField('title');
                $data['order_id'] = $value['order_id'];
                $data['dateline'] = time();
                $data['site_id'] = $site_id;
                $ordernum = D('order')->where(array('id' => $order_id, 'site_id' => $site_id))->getField('ordernumber');
                $name = D('Member')->where(array('site_id' => $site_id, 'id' => $value['member_id']))->getField('nickname');
                $data['remark'] = '会员：' . $name . '的订单.' . $pro_name . ',' . $num . '件，订单:' . $ordernum . '完成（已扣除分佣:'.$affmoneytotal.'）';
                $data['supplier_id'] = $value['supplier_id'];
                $data['user_id'] = session(C('USER_AUTH_KEY'))?session(C('USER_AUTH_KEY')):0;
                $add = D('supplier_account_log')->add($data);
                //写入账户
                if ($add) {
                    M('Supplier')->where(array('id' => $data['supplier_id']))->setInc('money', $data['changenum']);
					
					
					$sup=D('Member_supplier')->where(array('supplier_id'=>$data['supplier_id'],'site_id'=>$site_id))->find();
					if($sup){
						D('Member_account_log') -> change($data['changenum'], $sup['member_id'], $data['remark']);
				
					}
					
                }
            }
//是否存在分成
            /*$checkaff = D('Member_account_log')->where(array('order_id' => $order_id, 'pdstate' => 3))->sum('changenum');
            if ($checkaff > 0) {
                M('Supplier')->where(array('id' => $data['supplier_id']))->setInc('aff_money', $checkaff);
            }*/
			$acc_log=M('Member_account_log')->where(' order_id = '.$order_id.' and pdstate != 4 and pdstate != 0')->select();
	
			//exit(dump($acc_log));	
			 
			if($acc_log){
			
			
			if(file_exists('Lib/Action/Admin/AffiliatesettingAction.class.php')){
			include 'Lib/Action/Admin/AffiliatesettingAction.class.php';			
				}else{
			include '../Admin/AffiliatesettingAction.class.php';		
				}
			$aff=new AffiliatesettingAction();
			
			$attr='';
			foreach($acc_log as $k => $v){
			$sale=M('Sale')->where(' order_id = '.$v['order_id'])->select();
		
			foreach($sale as $sk => $sv){
			$_POST=array();
			if(!$attr){
			$attr=$sv['attr'];	
			}else{
			$attr.=';'.$sv['attr'];	
			}
				
			}
			
			$_POST['order_id'][]=$v['order_id'];
			$_POST['product_id'][]=$v['product_id'];
			$_POST['attr'][]=$attr;
			$aff->auto_confirm();
			}
			}
		
            return true;
        } else {
            $this->errorinfo = $this->getError();
            return false;
        }
    }
    //取消订单
    public function cancel($order_id, $site_id = 0)
    {
        if ($order_id == 0) {
            $this->errorinfo = '参数错误，订单ID错误';
            return false;
        }
        //是否能取消订单，未付款才能取消
        $order = $this->where(array('id' => $order_id, 'site_id' => $site_id))->find();
        if ($order['status'] != 1) {
            $this->errorinfo = '订单不能取消，可能是已经取消了！';
            return false;
        }
        $data['status'] = 0;
        $map['site_id'] = $site_id;
        $map['id'] = $order_id;
        $ret = $this->where($map)->data($data)->save();
        if ($ret !== false) {
            $this->errorinfo = '成功取消订单!';
            return true;
        } else {
            $this->errorinfo = $this->getError();
            return false;
        }
    }
    //更新退换货状态
    public function updatethstatus($order_id, $sale_id, $site_id, $thstatus = 0, $thnum = 0, $thtype, $remark = '', $shipping)
    {
        $saleDB = D('Sale');
        //$returngoodsDB = M('Returngoods');
        /*
        thstatus 退货类型
        0.默认/取消
        1.申请退货
        2.审核通过，请提供客户信息
        3.用户已经提交物流信息，待退货
        4.后台确认，退货完成
        5.管理员确认收退货，
        */
        $order = $this->where(array('id' => $order_id, 'site_id' => $site_id))->find();
        //未支付订单无售后
        if ($order['status'] != 2) {
            $this->errorinfo = '该订单未支付！';
            return false;
        }
        $sale = $saleDB->where(array('id' => $sale_id, 'site_id' => $site_id, 'order_id' => $order_id))->find();
        //货品不存在，不能售后
        if (!$sale) {
            $this->errorinfo = '货品不存在，不能售后！';
            return false;
        }
        //是否收货，如果不是收货状态，不能售后
        if ($sale['confirm'] == 0 && $sale['thtype'] != 3) {
            $this->errorinfo = '请您确认收货后，再申请售后！';
            return false;
        }
        //即将修改的状态与订单状态一致，此时不需要修改状态，直接反回FALSE
        if ($thstatus == $sale['thstatus']) {
            $this->errorinfo = '该订单的状态正确，不需要修改！';
            return false;
        }
        //数量超过了，不能申请
        if ($sale['num'] < $thnum && $thstatus == 1) {
            $this->errorinfo = '超出商品数量，请填写正确的数量！';
            return false;
        }
        $map['order_id'] = $order_id;
        $map['id'] = $sale_id;
        $map['site_id'] = $site_id;
        //取消退货
        if ($thstatus == 0) {
            if ($sale['thstatus'] == 4) {
                //已经完成的退货不能取消
                $this->errorinfo = '已经完成的退货操作不能取消！';
                return false;
            }
            $data['thstatus'] = 0;
            $data['thnum'] = 0;
            $data['thtype'] = 0;
        }
        //提交申请退货,原状态为0才能申请
        if ($sale['thstatus'] == 0 && $thstatus == 1) {
            $data['thstatus'] = 1;
            $data['thnum'] = $thnum;
            $data['thtype'] = $thtype;
        }
        //后台通过审核
        if ($sale['thstatus'] == 1 && $thstatus == 2) {
            $data['thstatus'] = 2;
        }
        //用户提交信息
        if ($sale['thstatus'] == 2 && $thstatus == 3) {
            $data['thstatus'] = 3;
            $data['couriernumber'] = $shipping['couriernumber'];
            $data['courier'] = $shipping['courier'];
        }
        //确认售后完成
        if (($sale['thstatus'] == 3 && $thstatus == 4) || ($sale['thstatus'] == 5 && $thstatus == 4 && $thtype == 2)) {
            $data['thstatus'] = 4;
        }
        //换货时后台发货
        if ($sale['thstatus'] == 3 && $thstatus == 5 && $thtype == 2) {
            $data['thstatus'] = 5;
            $data['couriernumber'] = $shipping['couriernumber'];
            $data['courier'] = $shipping['courier'];
        }
        //dump($data);exit;
		
        $ret = $saleDB->where($map)->data($data)->save();
        if ($ret !== false) {
            //写入日志
            $rlog["remark"] = $remark;
            $rlog["member_id"] = $order['member_id'];
            $rlog["sale_id"] = $sale_id;
            $rlog["time"] = time();
            $returngoodsDB = D('Returngoods');
            $returngoodsDB->add($rlog);
            ////如果是退货，扣回分成
            if (($thtype == 1 || $thtype == 3) && $data['thstatus'] == 4) {
                //退款到账户
                $refundRet = $saleDB->refund($sale_id, $sale['site_id'], $thnum);
			
                if ($refundRet) {
                    //退款成功后更新订单的状态
                    //service_status 0无状态,1退货,2换货,3部分退货,4全部退货
                    $paystatus = $saleDB->where(array('order_id' => $order_id, 'pay_status' => array('in', '2,3')))->group('pay_status')->Field('pay_status')->order('pay_status desc')->select();
                    $pst = 3;
                    foreach ($paystatus as $k => $v) {
                        $pst = $v['pay_status'];
                    }
                    if ($pst == 3) {
                        $orderUpdate['service_status'] = 6;
                    }
                    if ($pst == 2) {
                        $orderUpdate['service_status'] = 5;
                    }
                    $this->where(array('id' => $order_id))->data($orderUpdate)->save();
                    $memid=D('Sale')->where('id = '.$sale_id)->getfield('member_id');
                    $suppid=D('Supplier')->where('member_id = '.$memid)->getfield('id');
                    if($suppid){
                        $dataaa['service_status']=6;
                        D('Order_supplier')->where('order_id = '.$order_id.' and supplier_id = '.$suppid )->data($dataaa)->save();
                    }
                 } else {
                    $data['thstatus'] = 3;
                    $saleDB->where($map)->data($data)->save();
                    $this->errorinfo = '退款失败' . $saleDB->error;
                    return false;
                }
            }
            return true;
        } else {
            $this->errorinfo = $saleDB->getError();
            return false;
        }
    }
    public function finish($order_id, $site_id)
    {
        $map['id'] = $order_id;
        $map['site_id'] = $site_id;
        $order = $this->where($map)->find();
        if ($order['status'] != 2) {
            $this->errorinfo = '该订单未支付！';
            return false;
        }
        $ordernumber = $order['ordernumber'];
        $saleDB = M('Sale');
        $sale = $saleDB->where(array(
            'order_id' => $order_id
        ))->select();
        foreach ($sale as $k => $v) {
            if ($v['thstatus'] == 1 || $v['thstatus'] == 2 || $v['thstatus'] == 3 || $v['thstatus'] == 5) {
                $this->errorinfo = '订单正在售后，不能完成订单';
                return false;
            }
        }
        //修改订单为完成状态
        $ret = $orderDB->where(array(
            'id' => $order_id
        ))->save(array(
            'shipping_status' => 4
        ));
        if ($ret !== false) {
            $openid = M('Member')->where(array('id' => $order['member_id']))->getField('openid');
            $text = '订单号:' . $ordernumber . '已经完成，期待您下次再次光临！';
            sendWXMsg($openid, $text);
            return true;
        } else {
        }
    }
//    分供货商写入新表
    public function addgroups($orderId,$data){
//shippingid,供货商id,运费,总价,供货商名,oderID
        $data['total']=0;
        if($data['fee']){
            foreach($data['fee'] as $k => $v){
                $data['supplier_id']=explode(',',trim($v,','))[0];//供货商id
                $data['shipping_fee']=explode(',',trim($v,','))[1];//运费
                foreach($data['shipping'] as $kk=>$vv){
                    if(strpos($vv,','.$data['supplier_id'].',')!==false){
                        $data['shipping_id']=explode(',',trim($vv,','))[1];
                    }
                }
                foreach($data['pre'] as $key=>$val){
                    if(strpos($val,','.$data['supplier_id'].',')!==false){
                        $data['price']=explode(',',trim($val,','))[1];
                    }
                }
                $data['total']=$data['price']+$data['shipping_fee'];
                $data['order_id']=$orderId;
                D('Order_supplier')->add($data);
            }
        }
    }
}
